import Taro, {Component} from '@tarojs/taro'
import {View, OpenData, Input} from '@tarojs/components'
import { connect } from '@tarojs/redux'
import styles from './index.module.scss'
import { getUserInfo, changeBankCard, getHealthList, submitHealth } from '@/api/index'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction, AtIcon } from "taro-ui"
import PERSONAL_PROTOCOL from '@/assets/img/personal_protocol.png'

@connect(({user}) => ({
  info: user.info
}), dispatch => ({
}))
export default class User extends Component {

  config = {
    navigationBarTitleText: '个人信息'
  }

  state = {
    name: '',
    idCard: '',
    bankCard: '',
    region: '',
    jobNumber: '',
    isEditBank: false,
    newBank: '',
    healths: [],
    dictLabel: '',
    dictValue: '',
    isEditDisease: false,
    disease: ''
  }

  componentWillMount = () => {
    this.getUserInfo()
  }

  getUserInfo = async () => {
    const { mobile } = this.props.info
    try {
      const { data } = await getUserInfo({loginAccount: mobile})
      this.setState({name: data.name, idCard: data.idCard, bankCard: data.bankCardNum, region: data.region, jobNumber: data.jobNumber, disease: data.disease}, () => {
        this.getHealths(data)
      })
    } catch(e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  handleBankChange = () => {
    this.setState(pre => ({isEditBank: !pre.isEditBank, newBank: ''}))
  }

  handleDiseaseChange = () => {
    this.setState(pre => ({isEditDisease: !pre.isEditDisease, disease: ''}))
  }

  submitChange = async () => {
    try {
      const { newBank } = this.state
      const { info } = this.props
      const { mobile } = info
      if (!newBank) return Taro.showToast({title: '请输入新的银行卡号', icon: 'none', mask: false})
      Taro.showLoading({mask: false, title: '请稍后...'})
      const { data } = await changeBankCard({phone: mobile, bankCard: newBank})
      Taro.hideLoading()
      Taro.showToast({title: '设置成功'})
      this.handleBankChange()
      this.getUserInfo()
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  getHealths = async (userinfo) => {
    try {
      const { data } = await getHealthList({})
      if (userinfo.stateOfHealth) {
        const obj = data.find(item => item.dictValue === userinfo.stateOfHealth)
        this.setState({dictLabel: obj.dictLabel, dictValue: obj.dictValue})
      }
      this.setState({healths: data})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  handlerSelect = async (e) => {
    try {
      const { mobile } = this.props.info
      let dictLabel = this.state.healths[e.detail.value].dictLabel
      let dictValue = this.state.healths[e.detail.value].dictValue
      if (dictValue === '4') {
        this.setState({isEditDisease: true})
      }
      await submitHealth({loginAccount: mobile, stateOfHealth: dictValue})
      this.setState({dictLabel, dictValue})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  submitDiseaseChange = async () => {
    try {
      const { mobile } = this.props.info
      const { disease } = this.state
      await submitHealth({loginAccount: mobile, stateOfHealth: '4', disease})
      this.setState({isEditDisease: false})
    } catch (e) {
      Taro.showToast({title: e.message, icon: 'none'})
    }
  }

  render () {
    const { name, idCard, bankCard, region, jobNumber, isEditBank, newBank, dictValue, dictLabel, healths, isEditDisease, disease } = this.state
    return (
      <View className={styles.wrapper}>
        <View className={styles.container}>
          <View className={styles.avatarWrapper}>
            <View className={styles.avatar}>
              <OpenData type={'userAvatarUrl'}></OpenData>
            </View>
            <View className={styles.avatarContainer}>
              <View className={styles.name}>{name}</View>
              <View className={styles.idCard}>证件号码：{idCard}</View>
            </View>
          </View>
          <View className={styles.card}>
            <View className={styles.item}>
              <View className={styles.label}>姓名</View>
              <View className={styles.value}>{name}</View>
            </View>
            <View className={styles.item}>
              <View className={styles.label}>身份证号码</View>
              <View className={styles.value}>{idCard}</View>
            </View>
            <View className={styles.item}>
              <View className={styles.label}>银行卡号</View>
              <View className={styles.value}>{bankCard || ''} <Text onClick={this.handleBankChange} className={styles.theme}>{bankCard ? '更改' : '添加'}</Text></View>
            </View>
          </View>
          <View className={styles.card}>
            <View className={styles.item}>
              <View className={styles.label}>签约地区</View>
              <View className={styles.value}>{region || '暂无数据'}</View>
            </View>
            {
              jobNumber && <View className={styles.item}>
                <View className={styles.label}>签约编号</View>
                <View className={styles.value}>{jobNumber || '暂无数据'}</View>
              </View>
            }
            <View className={styles.item}>
              <View className={styles.label}>健康状况</View>
              <View className={styles.value}>
                <Picker mode="selector" range={healths} rangeKey="dictLabel" onChange={this.handlerSelect}>
                  <Input placeholder={'选择健康状况'} placeholderStyle={'color: #CCCCCC;'} className={styles.input} value={dictLabel} disabled></Input>
                  <AtIcon value='chevron-right' size='22' color='#CCCCCC' className={styles.icon}></AtIcon>
                </Picker>
              </View>
            </View>
          </View>
        </View>
        <View className={styles.footer}>
          <Image src={PERSONAL_PROTOCOL} className={styles.protocolImg}></Image>
          <View className={styles.protocol}>个人隐私信息安全保障中</View>
        </View>
        <AtModal isOpened={isEditBank} onClose={this.handleBankChange}>
          <AtModalHeader>修改银行卡号</AtModalHeader>
          <AtModalContent>
            {isEditBank && <Input className={styles.edit} type="number" placeholder="请输入银行卡号" value={newBank} onInput={(e) => this.setState({newBank: e.detail.value})}></Input>}
          </AtModalContent>
          <AtModalAction> <Button onClick={this.handleBankChange}>取消</Button> <Button onClick={this.submitChange}>确定</Button> </AtModalAction>
        </AtModal>
        <AtModal isOpened={isEditDisease} onClose={this.handleDiseaseChange}>
          <AtModalHeader>疾病原因</AtModalHeader>
          <AtModalContent>
            {isEditDisease && <Input className={styles.edit} type="number" placeholder="请输入疾病原因（可填写）" value={disease} onInput={(e) => this.setState({disease: e.detail.value})}></Input>}
          </AtModalContent>
          <AtModalAction> <Button onClick={this.handleDiseaseChange}>取消</Button> <Button onClick={this.submitDiseaseChange}>确定</Button> </AtModalAction>
        </AtModal>
      </View>
    )
  }
}
